package utils

import (
	"github.com/beego/beego/v2/core/logs"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func InitDB() {
	enable := viper.GetBool("database.enable")
	if enable {
		sqlConn := viper.GetString("database.dsn")
		o := NewDB(sqlConn)
		O = &o
	}
}

var O *Db

type Db struct {
	DB *gorm.DB
}

// NewDb 实例化
func NewDB(sqlConn string) Db {
	db, err := gorm.Open(mysql.Open(sqlConn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true, NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
		},
	})
	if err != nil {
		logs.Error("database init error: %s", err)
	}
	return Db{
		DB: db,
	}
}

// GetDB
func GetDB() *gorm.DB { return O.GetDB() }
func (__ *Db) GetDB() *gorm.DB {
	return __.DB
}
